﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Adaptive_Clustering
{
    public class Silhouette
    {
        int k;
        double[] SumSilhouette;
        double[] CountSilhouette;

        public Silhouette(int k)
        {
            this.k = k;
            SumSilhouette = new double[k];
            CountSilhouette = new double[k];
        }

        public void silhouette(Byte[,] ImageClusterIndexArray, int i, int j, int k)
        {
            double[] RegionDistancesOfPixel = new double[k];
            double Ax, Bx, Sx;

            RegionDistancesOfPixel = FindDistanceForPixel(i, j, ImageClusterIndexArray, k);
            Ax = RegionDistancesOfPixel[ImageClusterIndexArray[i, j]];
            if (ImageClusterIndexArray[i, j] == 0) //Set first value of Bx to be the first value of OTHER clusters
                Bx = RegionDistancesOfPixel[1];
            else
                Bx = RegionDistancesOfPixel[0];

            for (int z = 0; z < k; z++)
                if (z != ImageClusterIndexArray[i, j]) //only other clusters
                    if (Bx > RegionDistancesOfPixel[z])//if Bx not Min, set new Min
                        Bx = RegionDistancesOfPixel[z];
            Sx = (Bx - Ax) / (Math.Max(Ax, Bx));
            SumSilhouette[ImageClusterIndexArray[i, j]] += Sx;
            CountSilhouette[ImageClusterIndexArray[i, j]]++;
        }

        public double[] GetSum() { return SumSilhouette; }

        public double[] GetCount() { return CountSilhouette; }

        private double[] FindDistanceForPixel(int i, int j, byte[,] ImageClusterIndexArray, int k)
        {
            int x, y;
            double[] Sum = new double[k];
            double[] Count = new double[k];

            for (x = 0; x < ImageClusterIndexArray.GetLength(0); x++) //add distance to its region and count
                for (y = 0; y < ImageClusterIndexArray.GetLength(1); y++)
                {
                    Sum[ImageClusterIndexArray[x, y]] += (Math.Abs(i - x) + Math.Abs(j - y));
                    Count[ImageClusterIndexArray[x, y]]++;
                }
            for (int z = 0; z < k; z++) //AVG for each cluster
                Sum[z] = Sum[z] / Count[z]++;

            return Sum;
        }
    }
}
